package com.kuaifawu.lwnlawyerclient.Lib.photoselector.ui;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.media.MediaScannerConnection;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.kuaifawu.lwnlawyerclient.LWNNetwork.LWNNetworkCenter;
import com.kuaifawu.lwnlawyerclient.Lib.KFWActivityCenter;
import com.kuaifawu.lwnlawyerclient.Lib.ToastView_custom;
import com.kuaifawu.lwnlawyerclient.Lib.photoselector.model.PhotoModel;
import com.kuaifawu.lwnlawyerclient.R;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;


public class BasePhotoPreviewActivity extends Activity implements OnPageChangeListener, OnClickListener {

    private ViewPager mViewPager;
    private RelativeLayout layoutTop;
    private ImageButton btnBack;
    private ImageButton btnDelete;
    private TextView tvPercent;
    protected List<PhotoModel> photos;
    protected int current;
    private ArrayList<PhotoModel> scanPhotos=null;

    Activity activity_this;

    ArrayList<String>filepath;
    ArrayList<String>filename;
    //private ProgressDialog progressDialog=null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activity_this = this;

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_photopreview);
        layoutTop = (RelativeLayout) findViewById(R.id.layout_top_app);
        btnBack = (ImageButton) findViewById(R.id.btn_back_app);
        btnDelete = (ImageButton) findViewById(R.id.btn_delete_app);
        tvPercent = (TextView) findViewById(R.id.tv_percent_app);
        mViewPager = (ViewPager) findViewById(R.id.vp_base_app);

        btnBack.setOnClickListener(this);
        btnDelete.setOnClickListener(this);
        mViewPager.setOnPageChangeListener(this);
        filepath = new ArrayList<String>();
        filename = new ArrayList<String>();

        Button btn_send = (Button)findViewById(R.id.btn_send_app);
        if(KFWActivityCenter.getInstance().getTakephoto_state() == 1){
            btn_send.setVisibility(View.VISIBLE);
            btn_send.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    compressedPicshow();

                }
            });
        }

        overridePendingTransition(R.anim.activity_alpha_action_in, 0);
        //showpProgress();
    }

    private  ProgressDialog  progressDialogshow=null;
    public void compressedPicshow(){
        progressDialogshow=new ProgressDialog(BasePhotoPreviewActivity.this);
        progressDialogshow.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialogshow.setTitle("图片正在处理中");
        progressDialogshow.setMessage("请稍后。。。");
        progressDialogshow.setCanceledOnTouchOutside(false);// 设置在点击Dialog外是否取消Dialog进度条

        progressDialogshow.show();

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    for (int i = 0; i < photos.size(); i++) {
                        PhotoModel model = photos.get(i);
                        PhotoModel comModel=PhotoSelectorActivity.compressedPic(model.getOriginalPath(),i);
                        if(comModel!=null){
                            photos.remove(i);
                            photos.add(i,comModel);
                        }

                    }

                    handler.sendEmptyMessage(1);


                }catch (Exception e){
                    e.printStackTrace();
                }

            }
        }).start();





    }
    protected void bindData() {
        mViewPager.setAdapter(mPagerAdapter);
        mViewPager.setCurrentItem(current);

    }

    private PagerAdapter mPagerAdapter = new PagerAdapter() {

        @Override
        public int getCount() {
            if (photos == null) {
                return 0;
            } else {
                return photos.size();
            }
        }

        @Override
        public View instantiateItem(final ViewGroup container, final int position) {
            PhotoPreview photoPreview = new PhotoPreview(getApplicationContext());

            ((ViewPager) container).addView(photoPreview);
            photoPreview.loadImage(photos.get(position));
            photoPreview.setOnClickListener(photoItemClickListener);
            return photoPreview;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public int getItemPosition(Object object) {
            return POSITION_NONE ;
        }
    };
    protected boolean isUp;
    public void getScanlist(){
        scanPhotos=new ArrayList<PhotoModel>();
        if(photos!=null&&photos.size()>0){
           for(int i=0;i<photos.size();i++){
         scanPhotos.add(photos.get(i));
        }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_back_app: {
                getScanlist();
                Intent intent=new Intent();
                Bundle bundle=new Bundle();
                bundle.putSerializable("scanphotos",scanPhotos);
                intent.putExtras(bundle);
                setResult(110,intent);
                finish();
            }
            break;
            case R.id.btn_delete_app: {
                photos.remove(mViewPager.getCurrentItem());
                mPagerAdapter.notifyDataSetChanged();
                tvPercent.setText("预览" + "(" + (current + 1) + "/" + photos.size() + ")");
                if(current + 1>photos.size()){
                    setResult(70);
                    finish();
                }
                //mViewPager.removeView(mViewPager.getChildAt(mViewPager.getCurrentItem()));
                //finish();
            }
            break;
        }
    }

    @Override
    public void onPageScrollStateChanged(int arg0) {

    }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {

    }

    @Override
    public void onPageSelected(int arg0) {
        current = arg0;
        updatePercent();
    }

    protected void updatePercent() {
        tvPercent.setText("预览" + "(" + (current + 1) + "/" + photos.size() + ")");
    }

    private OnClickListener photoItemClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!isUp) {
                //new AnimationUtil(getApplicationContext(), R.anim.translate_up)
                //		.setInterpolator(new LinearInterpolator()).setFillAfter(true).startAnimation(layoutTop);
                //isUp = true;
            } else {
                //new AnimationUtil(getApplicationContext(), R.anim.translate_down_current)
                //		.setInterpolator(new LinearInterpolator()).setFillAfter(true).startAnimation(layoutTop);
                //isUp = false;
            }
        }
    };

    /**
     * 上传图片
     */
    public void upLoadPic(int picId) {
       final ProgressDialog  progressDialog=new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setTitle("第"+(picId+1)+"张正在发送");
        progressDialog.setProgress(0);
//        progressDialog.setMax(100);
         progressDialog.show(); // 显示进度条
       // final ProgressDialog proDialog = android.app.ProgressDialog.show(activity_this, "", "上传中，请稍候");
        final LWNNetworkCenter center = LWNNetworkCenter.getInstance();
        PhotoModel model = photos.get(picId);
        //RequestParams params = center.getInstance().uploadPic("0", KFWActivityCenter.getInstance().getOrder_id(), model.getOriginalPath(), activity_this);
        RequestParams params = null;
        HttpUtils http = center.getUtils();
        http.configCurrentHttpCacheExpiry(0*0);
        http.send(HttpRequest.HttpMethod.POST,
                center.LWNBaseUrl_POST + "api/orders/uploadFileToTmp", params,
                new RequestCallBack<Object>() {
                    @Override
                    public void onSuccess(ResponseInfo<Object> objectResponseInfo) {
                     //   proDialog.dismiss();
                        progressDialog.dismiss();
                        try {
                            JSONObject jsonObject = new JSONObject(objectResponseInfo.result.toString());
                            String string_code = jsonObject.getString("code");
                            String string_msg = jsonObject.getString("msg");
                            if (string_code.equals("1")) {
                                JSONObject data = jsonObject.getJSONObject("data");
                                filepath.add(data.getString("filepath"));
                                filename.add(data.getString("filename"));
                                handler.sendEmptyMessage(2);
                                picid++;
                                return;
                            }
                            ToastView_custom toast = new ToastView_custom(activity_this);
                            toast.showCustom(activity_this, string_msg);
                        } catch (Exception e) {
                            e.printStackTrace();
                          //  proDialog.dismiss();
                            progressDialog.dismiss();
                        }

                    }

                    @Override
                    public void onFailure(HttpException e, String s) {
                        //System.out.println(s);
                       //proDialog.dismiss();
                        ToastView_custom toast = new ToastView_custom(activity_this);
                        toast.showCustom(activity_this, "网络不稳定，请稍后重试");
                        progressDialog.dismiss();
                    }

                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                        progressDialog.setMax((int)total);
                        progressDialog.setProgress((int)current);


//                        progressDialog.setMax(100);
//                       int curr=(int)((current/total)*100);
//                        if(curr<100){
//                            progressDialog.setProgress(curr);
//                        }else if(curr==100){
//                            progressDialog.dismiss();
//                        }

                    }
                });
        }


        /**
         * 发送状态
         */
        public void sendPic() {
            LWNNetworkCenter center = LWNNetworkCenter.getInstance();
            //RequestParams params = center.getInstance().saveUppic(KFWActivityCenter.getInstance().getOrder_id(), filename, filepath, activity_this);
            RequestParams params = null;

            HttpUtils http = center.getUtils();
            http.send(HttpRequest.HttpMethod.POST,
                    center.LWNBaseUrl_POST + "api/orders/saveUploadFile", params,
                    new RequestCallBack<Object>() {
                        @Override
                        public void onSuccess(ResponseInfo<Object> objectResponseInfo) {

                            try {
                                JSONObject jsonObject = new JSONObject(objectResponseInfo.result.toString());
                                String string_code = jsonObject.getString("code");
                                String string_msg = jsonObject.getString("msg");

                                if (string_code.equals("1")) {
                                    TimerTask task = new TimerTask() {
                                        public void run() {
                                            setResult(100);
                                            finish();
                                        }
                                    };
                                    Timer timer = new Timer();
                                    timer.schedule(task, 1 * 1000);

                                    ToastView_custom toast = new ToastView_custom(activity_this);
                                    toast.showCustom(activity_this,  string_msg);
                                } else {

                                    ToastView_custom toast = new ToastView_custom(activity_this);
                                    toast.showCustom(activity_this, string_msg);
                                }

                            } catch (Exception e) {
                                e.printStackTrace();
                                //proDialog.dismiss();
                            }

                        }

                        @Override
                        public void onFailure(HttpException e, String s) {
                            //System.out.println(s);
                            //proDialog.dismiss();
                        }

                        @Override
                        public void onLoading(long total, long current, boolean isUploading) {

                        }
                    }
            );
        }
    //private int count=0;
//    private void showpProgress(){
//        for (int i = 0; i <photos.size() ; i++) {
//           new Thread(new Runnable() {
//                @Override
//                public void run() {
//                    try{
//                        Thread.sleep(5000);
//                    }catch (Exception e){
//                        e.printStackTrace();
//                    }
//
//                }
//            }).start();
//            upLoadPic(i);
//        }
//
//
//    }
            private int picid=0;
            private Handler handler=new Handler(){
                        @Override
                    public void handleMessage(Message msg) {
                           super.handleMessage(msg);
                            switch (msg.what){
                                case 2:
                                    if(picid<photos.size()){
                                        upLoadPic(picid);
                                    }else{
                                        File file = new File("/sdcard/Image_kuai/");
                                        recursionDeleteFile(file);
                                        MediaScannerConnection.scanFile(BasePhotoPreviewActivity.this,
                                                new String[]{Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getPath()}, null, null);
                                        sendPic();
                                    }

                                    break;
                                case 1:
                                    progressDialogshow.dismiss();
                                    upLoadPic(picid);

                                    break;
                            }
             }
            };


       public  void deletCompressPhoto(){
           File file = new File("/sdcard/Image_kuai/");
           getContentResolver().delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, MediaStore.Images.Media.DATA + "=?", new String[]{file.getPath()});
           MediaScannerConnection.scanFile(this,
                   new String[]{Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getPath()}, null, null);
             }
   // File[] childFile = file.listFiles();
    public static void recursionDeleteFile(File file){
        if(file.isFile()){
            file.delete();
            return;
        }
        if(file.isDirectory()){
            File[] childFile = file.listFiles();
            if(childFile == null || childFile.length == 0){
                file.delete();
                return;
            }
            for(File f : childFile){
                recursionDeleteFile(f);
            }
            file.delete();
        }


    }

}
